﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using Medianamik.Core.Urls;
using System.Globalization;

namespace Medianamik.Core.Sugar
{
    /// <summary>
    /// Remplace les Guid trouvées dans le contenu par
    /// l'url correspondante
    /// </summary>
    public class LinkResolver
    {
        protected virtual IUrlDictionary Urls
        {
            get;
            private set;

        }

        protected virtual CultureInfo Culture
        {
            get;
            private set;
        }

        public LinkResolver(CultureInfo pCulture, IUrlDictionary pUrls)
        {
            if (pCulture == null)
            {
                throw new ArgumentNullException("pCulture");
            }
            if (pUrls == null)
            {
                throw new ArgumentNullException("pUrls");
            }
            Culture = pCulture;
            Urls = pUrls;
        }

        public virtual string Resolve(string pContent)
        {
            bool dummy;

            return Resolve(pContent, out dummy);
        }

        public virtual string Resolve(string pContent, out bool pFound)
        {
            var f = false;
            var content = pContent ?? string.Empty;
            var result = content;

            result = DecodeHrefUrl(result);

            if (!content.Contains("href=\"", StringComparison.OrdinalIgnoreCase))
                result = "href=\"" + content;

            MatchEvaluator func = (m) => { f = true; return content.StartsWith(".@") ? MatchEvaluator(m) : "href=\"" + MatchEvaluator(m); };
            result = RegularExpressions.MedianamikLink.Replace(result, func);
            pFound = f;

            return pFound ? result : content;
        }

        private string DecodeHrefUrl(string result)
        {
            return RegularExpressions.HrefUrl.Replace(result,
                m => HttpUtility.UrlDecode(m.Value));
        }

        private string MatchEvaluator(Match match)
        {
            var result = "#";

            var cultureGroup = match.Groups["culture"];

            if (cultureGroup != null && cultureGroup.Value != null &&
                        cultureGroup.Value.Length > 9)
            {
                //Remove |culture=
                var cultureName = cultureGroup.Value.Substring(9, cultureGroup.Value.Length - 9);
                CultureInfo culture = null;

                if (StringHelper.IsCulture(cultureName, ref culture))
                    Culture = culture;
            }

            var nodeId = new Guid(match.Groups["id"].Value);
            var entries = Urls.GetEntries(nodeId, Culture).ToArray();

            if (entries.Length > 0)
            {
                //result = entries[0].RequestedUrl.ToString(); (Voir Maxime - ça serait top beau)
                result = entries[0].RequestedPath; 

                var anchorGroup = match.Groups["anchor"];
                var protocolGroup = match.Groups["protocol"];

                if (protocolGroup != null && protocolGroup.Value != null &&
                    protocolGroup.Value.Length > 10)
                {
                    var protocol = protocolGroup.Value.Substring(10,
                        protocolGroup.Value.Length - 10);

                    if (protocol == "http" || protocol == "https")
                    {
                        result = entries[0].RequestedUrl.ToString();
                        result = result.Substring(result.IndexOf(':'), result.Length - result.IndexOf(':'));

                        if (protocol == "http")
                            result = "http" + result;
                        else
                            result = "https" + result;
                    }

                }

                if (anchorGroup != null && anchorGroup.Value != null &&
                    anchorGroup.Value.Length > 8)
                {
                    result += "#" + anchorGroup.Value.Substring(8, anchorGroup.Value.Length - 8);
                }
            }

            return result;
        }
    }
}